package com.xmtlxx.web.controller.wms.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.IdUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.xmtlxx.common.core.domain.PageQuery;
import com.xmtlxx.common.core.page.TableDataInfo;
import com.xmtlxx.common.enums.PropertyLogType;
import com.xmtlxx.common.exception.ServiceException;
import com.xmtlxx.common.tengbo.vo.SmartCabinetPutProtVo;
import com.xmtlxx.common.utils.JsonUtils;
import com.xmtlxx.common.utils.StringUtils;
import com.xmtlxx.oms.domain.Property;
import com.xmtlxx.oms.domain.vo.PropertyVo;
import com.xmtlxx.oms.mapper.BoxDeptMapper;
import com.xmtlxx.oms.mapper.BoxMapper;
import com.xmtlxx.oms.mapper.PropertyLogMapper;
import com.xmtlxx.oms.mapper.PropertyMapper;
import com.xmtlxx.system.domain.SysOss;
import com.xmtlxx.system.domain.bo.SysOssBo;
import com.xmtlxx.system.mapper.SysDeptMapper;
import com.xmtlxx.system.mapper.SysOssMapper;
import com.xmtlxx.system.service.ISysDictDataService;
import com.xmtlxx.web.controller.center.service.ICommonService;
import com.xmtlxx.web.controller.wms.service.IPutDtlService;
import com.xmtlxx.wms.domain.*;
import com.xmtlxx.wms.domain.bo.InventoryBo;
import com.xmtlxx.wms.domain.bo.PutDtlBo;
import com.xmtlxx.wms.domain.vo.*;
import com.xmtlxx.wms.mapper.*;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.time.DateFormatUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;
import java.util.stream.Collectors;

/**
 * 上架任务明细Service业务层处理
 *
 * @author xmtlxx
 * @date 2022-08-15
 */
@Slf4j
@RequiredArgsConstructor
@Service
public class PutDtlServiceImpl implements IPutDtlService {

    private final PutDtlMapper baseMapper;

    private final LocatorMapper locatorMapper;

    private final PropertyMapper propertyMapper;

    private final InventoryMapper inventoryMapper;

    private final ISysDictDataService dictDataService;

    private final SysDeptMapper deptMapper;

    private final PutTaskMapper putTaskMapper;

    private final CabinetGroupMapper cabinetGroupMapper;

    private final CabinetMapper cabinetMapper;

    private final StoreAreaMapper storeAreaMapper;

    private final SysOssMapper ossMapper;

    private final BoxMapper boxMapper;

    private final BoxDeptMapper boxDeptMapper;

    private final WarehouseMapper warehouseMapper;

    private final PropertyLogMapper propertyLogMapper;

    private final SmartCabinetCodeMapper smartCabinetCodeMapper;

    private final ICommonService commonService;

    /**
     * 查询上架任务明细
     *
     * @param id 上架任务明细主键
     * @return 上架任务明细
     */
    @Override
    public PutDtlVo queryById(String id) {
        //return baseMapper.selectVoById(id);
        return baseMapper.selectPutDtlVoByID(id);
    }

    /**
     * 查询上架任务明细列表
     *
     * @param bo 上架任务明细
     * @return 上架任务明细
     */
    @Override
    public TableDataInfo<PutDtlVo> queryPageList(PutDtlBo bo, PageQuery pageQuery) {
        // LambdaQueryWrapper<PutDtl> lqw = buildQueryWrapper(bo);
        // Page<PutDtlVo> result = baseMapper.selectVoPage(pageQuery.build(), lqw);
        Page<PutDtlVo> result = baseMapper.selectPagePutDtlList(pageQuery.build(), bo);
        return TableDataInfo.build(result);
    }

    /**
     * 查询上架任务明细列表
     *
     * @param bo 上架任务明细
     * @return 上架任务明细
     */
    @Override
    public List<PutDtlVo> queryList(PutDtlBo bo) {
        // LambdaQueryWrapper<PutDtl> lqw = buildQueryWrapper(bo);
        // return baseMapper.selectVoList(lqw);
        bo.setDelFlag("0");
        List<PutDtlVo> results = baseMapper.selectPutDtlList(bo);
        List<String> ids = results.stream().map(PutDtlVo::getId).collect(Collectors.toList());
        SysOssBo ossBo = new SysOssBo();
        ossBo.setObjIds(ids);
        ossBo.setBuss("putDtl");
        List<SysOss> ossList = ossMapper.selectSysOssList(ossBo);
        if (results != null && results.size() > 0) {
            results = results.stream().map(item -> {
                PutDtlVo dtl = new PutDtlVo();
                BeanUtil.copyProperties(item, dtl);
                List<SysOss> ossFilterList =
                        ossList.stream().filter(oss -> oss.getObjid().equals(item.getId())).collect(Collectors.toList());
                if (CollectionUtil.isNotEmpty(ossFilterList)) {
                    dtl.setOss(ossFilterList);
                } else {
                    dtl.setOss(new ArrayList<>());
                }
                return dtl;
            }).collect(Collectors.toList());
        }
        return results;
    }

    private LambdaQueryWrapper<PutDtl> buildQueryWrapper(PutDtlBo bo) {

        Map<String, Object> params = bo.getParams();
        LambdaQueryWrapper<PutDtl> lqw = Wrappers.lambdaQuery();
        lqw.eq(StringUtils.isNotBlank(bo.getTaskId()), PutDtl::getTaskId, bo.getTaskId());
        lqw.eq(StringUtils.isNotBlank(bo.getPno()), PutDtl::getPno, bo.getPno());
        lqw.like(StringUtils.isNotBlank(bo.getName()), PutDtl::getName, bo.getName());
        lqw.eq(StringUtils.isNotBlank(bo.getStoreId()), PutDtl::getStoreId, bo.getStoreId());
        lqw.eq(StringUtils.isNotBlank(bo.getAreaId()), PutDtl::getAreaId, bo.getAreaId());
        lqw.eq(StringUtils.isNotBlank(bo.getLocatorId()), PutDtl::getLocatorId, bo.getLocatorId());
        lqw.eq(StringUtils.isNotBlank(bo.getStatus()), PutDtl::getStatus, bo.getStatus());
        lqw.eq(bo.getOperator() != null, PutDtl::getOperator, bo.getOperator());
        lqw.between(params.get("beginPutTime") != null && params.get("endPutTime") != null,
                PutDtl::getPutTime, params.get("beginPutTime"), params.get("endPutTime"));
        lqw.eq(StringUtils.isNotBlank(bo.getDelFlag()), PutDtl::getDelFlag, bo.getDelFlag());
        return lqw;
    }

    /**
     * 新增上架任务明细
     *
     * @param bo 上架任务明细
     * @return 结果
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean insertByBo(PutDtlBo bo) {

        PutDtl add = BeanUtil.toBean(bo, PutDtl.class);
        validEntityBeforeSave(add);

        //填充UUID
        add.setId(IdUtil.simpleUUID());
        add.setDelFlag("0");
        boolean flag = baseMapper.insert(add) > 0;
        if (flag) {
            bo.setId(add.getId());
        }
        return flag;
    }

    /**
     * 修改上架任务明细
     *
     * @param bo 上架任务明细
     * @return 结果
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public PutDtlVo updateByBo(PutDtlBo bo) {

        PutDtlVo vo = new PutDtlVo();
        PutDtl update = BeanUtil.toBean(bo, PutDtl.class);
        validEntityBeforeSave(update);
        if (!StringUtils.isEmpty(bo.getLocatorId())) {
            Locator locator = locatorMapper.selectById(bo.getLocatorId());
            update.setStoreId(locator.getStoreId());
        }

        String qrcode = update.getQrcode();
        String[] qstrs = qrcode.split("/");

        String key = qstrs[1] + "/" + qstrs[2] + "/";

        /**
         * 查询旧dlt数据,qrcode是否为空
         */
        long result = 0l;
        PutDtl old = baseMapper.selectById(update.getId());

        PutTask putTask = putTaskMapper.selectById(old.getTaskId());
        Warehouse warehouse = warehouseMapper.selectById(putTask.getWid());
        /**
         * 变更库位使用状态
         */
        if (StringUtils.isNotBlank(old.getLocatorId())) {
            Locator oldLocator = locatorMapper.selectById(old.getLocatorId());
            if (warehouse.getBuss().equals("1")) {
                oldLocator.setStatus("0");
            } else {
                if (oldLocator.getStatus().equals("2")) {//已满
                    oldLocator.setStatus("1");//已使用
                } else if (oldLocator.getStatus().equals("1")) {
                    //查询当前库位下的物品剩余
                    InventoryBo inventoryBo = new InventoryBo();
                    inventoryBo.setLocatorId(oldLocator.getId());
                    inventoryBo.setStatus("0");//在库物品
                    List<InventoryVo> inventories = inventoryMapper.selectInventoryList(inventoryBo);
                    if (inventories != null && inventories.size() == 1) {//当前库位剩余物品只有本物品时
                        oldLocator.setStatus("0");//重置为待使用
                    }
                }
            }
            locatorMapper.updateById(oldLocator);
        }


        if (StringUtils.isEmpty(old.getQrcode())) {
            /**
             * 查询dtl中，当前库位最新编号
             */
//            LambdaQueryWrapper<PutDtl> plqw = Wrappers.lambdaQuery();
//            plqw.like(PutDtl::getQrcode,key);
//            long putDtlNum = baseMapper.selectCount(plqw);
            Long putDtlNum = 0l;
            if (qstrs[0].equals("CL")) {
                putDtlNum = baseMapper.countCars(key, qstrs[4]);
            } else {
                putDtlNum = baseMapper.countProperties(key);
            }

            if (putDtlNum == 0) {
                result = 1;
            } else {
                result = putDtlNum + 1;
            }
        } else {
            if (qstrs[0].equals("CL")) {
                String oldQrcode = old.getQrcode();
                String[] strs = oldQrcode.split("/");
                result = Integer.parseInt(strs[strs.length - 2]);
            } else if (qstrs[0].equals("DX")) {
                String oldQrcode = old.getQrcode();
                String[] strs = oldQrcode.split("/");
                if (oldQrcode.startsWith("CL")) {
                    result = Integer.parseInt(strs[strs.length - 2]);
                } else {
                    result = Integer.parseInt(strs[strs.length - 1]);
                }
            } else {
                String oldQrcode = old.getQrcode();
                String[] strs = oldQrcode.split("/");
                result = Integer.parseInt(strs[strs.length - 1]);
            }

            //变更库位日志
            String logContent =
                    "上架任务变更库位：(物品编号：" + bo.getPno() + "，物品名称：" + bo.getName() + ",变更" + old.getQrcode() + "至" + qrcode + ")";
            String info = JsonUtils.toJsonString(bo);
            commonService.savePropertyLog(bo.getPno(), update.getId(), bo.getName(),
                    PropertyLogType.PUT_TASK.getCode(), logContent, putTask.getDeptId(), info, bo.getStoreId(),
                    update.getNums(), null);
        }

        if (qstrs[0].equals("CL")) {
            qstrs[5] = String.valueOf(result);
            String code = StringUtils.join(qstrs, "/");
            update.setQrcode(code);
        } else {
            update.setQrcode(qrcode + result);
        }
        update.setStatus("0");//变更为待上架
        boolean flag = baseMapper.updateById(update) > 0;
        putTask.setStatus("0");
        putTaskMapper.updateById(putTask);

        Property property = propertyMapper.selectOne(new LambdaQueryWrapper<Property>().eq(Property::getPno, update.getPno()));
        if (property != null && update.getStatus() == "1") {
//            PropertyVo pvo = propertyMapper.selectPropertyVoByPno(property.getPno());
//            PropertyLog propertyLog = new PropertyLog();
//            propertyLog.setId(IdUtil.simpleUUID());
//            propertyLog.setLogType("6");
//            propertyLog.setObjid(putTask.getId());
//            propertyLog.setLogTime(new Date());
//            propertyLog.setUserId(LoginHelper.getUserId());
//            propertyLog.setOperator(LoginHelper.getUsername());
//            propertyLog.setDeptId(putTask.getDeptId());
//            propertyLog.setPno(pvo.getPno());
//            propertyLog.setName(pvo.getName());
//            propertyLog.setStoreId(update.getStoreId());
//            propertyLog.setNums(property.getNums());
//            String content = "【库位变更】原库位："
//                +pvo.getStore()+"/"+pvo.getArea()
//                +(!StringUtils.isEmpty(pvo.getGroupName())?pvo.getGroupName()+"/":"")
//                +(!StringUtils.isEmpty(pvo.getCabinetName())?pvo.getCabinetName()+"/":"")
//                +(!StringUtils.isEmpty(pvo.getLocator())?pvo.getLocator():"")
//                ;
//            propertyLog.setContent(content);

            property.setLocatorId(update.getLocatorId());
            property.setQrcode(update.getQrcode());
            property.setBelongStoreId(update.getStoreId());
            propertyMapper.updateById(property);

//            propertyLogMapper.insert(propertyLog);
        }
        if (flag) {
            BeanUtil.copyProperties(update, vo);

            Locator locator = locatorMapper.selectById(vo.getLocatorId());
            if (locator.getStatus().equals("0")) {
                locator.setStatus("1");
            }
            vo.setLocatorName(locator.getName());
            vo.setAreaName(storeAreaMapper.selectStoreAreaVoByID(locator.getAreaId()).getName());
            vo.setGroupName(cabinetGroupMapper.selectCabinetGroupVoByID(locator.getCabinetGroupId()).getName());
            if (!StringUtils.isEmpty(locator.getCabinetId())) {
                vo.setCabinetName(cabinetMapper.selectCabinetVoByID(locator.getCabinetId()).getName());
            }
            locatorMapper.updateById(locator);

            InventoryBo inventoryBo = new InventoryBo();
            inventoryBo.setPno(update.getPno());
            inventoryBo.setStoreId(update.getStoreId());
            InventoryVo inventory = inventoryMapper.selectInventoryByBo(inventoryBo);
            Inventory inBo = new Inventory();
            BeanUtil.copyProperties(inventory, inBo);
            if (inventory != null) {
                inBo.setStoreId(update.getStoreId());
                inBo.setAreaId(update.getAreaId());
                inBo.setLocatorId(update.getLocatorId());
                inBo.setQrcode(update.getQrcode());
                inBo.setBoxNo(update.getBoxNo());

                Long transfers = inventory.getTnums() != null ? inventory.getTnums() : 0l;
                Long deals = inventory.getDeals() != null ? inventory.getDeals() : 0l;
                Long returnNums = inventory.getRnums() != null ? inventory.getRnums() : 0l;

                Long realNums = bo.getNums() - transfers - deals + returnNums;
                inBo.setInnums(update.getNums());
                inBo.setNums(realNums);
                inBo.setDeptId(property.getOfficeId());
                inBo.setIntime(new Date());

                inventoryMapper.insertOrUpdate(inBo);
            } else {
                Inventory add = BeanUtil.toBean(bo, Inventory.class);
                add.setId(IdUtil.simpleUUID());
                add.setDeptId(property.getOfficeId());
                add.setIntime(new Date());
                add.setInnums(update.getNums());
                add.setOutnums(0l);
                add.setDeals(0l);
                add.setTnums(0l);
                add.setRnums(0l);
                add.setStatus("0");
                add.setDelFlag("0");
                inventoryMapper.insert(add);
            }

        }

        return vo;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public PutDtlVo updateByLocatorId(PutDtlBo bo) {

        PutDtlVo vo = new PutDtlVo();
        PutDtl update = BeanUtil.toBean(bo, PutDtl.class);
        validEntityBeforeSave(update);
        if (!StringUtils.isEmpty(bo.getLocatorId())) {
            Locator locator = locatorMapper.selectById(bo.getLocatorId());
            update.setStoreId(locator.getStoreId());
        }

        String qrcode = update.getQrcode();
        String[] qstrs = qrcode.split("/");

        String key = qstrs[1] + "/" + qstrs[2] + "/";

        /**
         * 查询旧dlt数据,qrcode是否为空
         */
        long result = 0l;
        PutDtl old = baseMapper.selectById(update.getId());

        PutTask putTask = putTaskMapper.selectById(old.getTaskId());


        if (StringUtils.isEmpty(old.getQrcode())) {
            /**
             * 查询dtl中，当前库位最新编号
             */
//            LambdaQueryWrapper<PutDtl> plqw = Wrappers.lambdaQuery();
//            plqw.like(PutDtl::getQrcode,key);
//            long putDtlNum = baseMapper.selectCount(plqw);
            Long putDtlNum = 0l;
            if (qstrs[0].equals("CL")) {
                putDtlNum = baseMapper.countCars(key, qstrs[4]);
            } else {
                putDtlNum = baseMapper.countProperties(key);
            }

            if (putDtlNum == 0) {
                result = 1;
            } else {
                result = putDtlNum + 1;
            }
        } else {
            if (qstrs[0].equals("CL")) {
                String oldQrcode = old.getQrcode();
                String[] strs = oldQrcode.split("/");
                result = Integer.parseInt(strs[strs.length - 2]);
            } else if (qstrs[0].equals("DX")) {
                String oldQrcode = old.getQrcode();
                String[] strs = oldQrcode.split("/");
                if (oldQrcode.startsWith("CL")) {
                    result = Integer.parseInt(strs[strs.length - 2]);
                } else {
                    result = Integer.parseInt(strs[strs.length - 1]);
                }
            } else {
                String oldQrcode = old.getQrcode();
                String[] strs = oldQrcode.split("/");
                result = Integer.parseInt(strs[strs.length - 1]);
            }

        }

        if (qstrs[0].equals("CL")) {
            qstrs[5] = String.valueOf(result);
            String code = StringUtils.join(qstrs, "/");
            update.setQrcode(code);
        } else {
            update.setQrcode(qrcode + result);
        }
        boolean flag = baseMapper.updateById(update) > 0;
        if (flag) {
            BeanUtil.copyProperties(update, vo);
            LocatorVo locatorVo = locatorMapper.selectLocatorVoByID(vo.getLocatorId());
            vo.setStoreName(locatorVo.getStoreName());
            vo.setAreaName(locatorVo.getAreaName());
            vo.setAreaNo(locatorVo.getAreaNo());
            vo.setGroupName(locatorVo.getGroupName());
            vo.setCabinetName(locatorVo.getCabinetName());
            vo.setLocatorName(locatorVo.getName());
        }
        return vo;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean updateByPutTak(PutDtlBo bo) {

        boolean flag = false;
        Warehouse warehouse = null;
        PutTask putTask = null;
        if (bo.getItems() != null && bo.getItems().size() > 0) {
            for (PutDtlVo vo : bo.getItems()) {
                PutDtl update = BeanUtil.toBean(vo, PutDtl.class);
                validEntityBeforeSave(update);
                if (putTask == null) {
                    putTask = putTaskMapper.selectById(update.getTaskId());
                    warehouse = warehouseMapper.selectById(putTask.getWid());
                }

                if (warehouse == null || StringUtils.isEmpty(warehouse.getIsSign()) || !warehouse.getIsSign().equals("1")) {
                    throw new ServiceException("入库单未签收，请签收后上架！");
                }

                if (StringUtils.isEmpty(update.getLocatorId())) {
                    throw new ServiceException("请选择库位后在上架！");
                }
                /**
                 * 新增/更新保管箱
                 */

//                Box box = boxMapper.selectOne(new LambdaQueryWrapper<Box>().eq(Box::getBoxNo,vo.getBoxNo()));
//                if(box == null){
//                    box = new Box();
//                    box.setId(IdUtil.simpleUUID());
//                    box.setBoxNo(vo.getBoxNo());
//                    box.setDeptId(LoginHelper.getDeptId());
//                    box.setCreateDept(LoginHelper.getDeptId());
//                    box.setDelFlag("0");
//                    box.setStatus("1");
//                    boxMapper.insert(box);
//
//                    BoxDept boxDept = new BoxDept();
//                    boxDept.setId(IdUtil.simpleUUID());
//                    boxDept.setBoxId(box.getId());
//                    boxDept.setBoxNo(box.getBoxNo());
//                    boxDept.setBoxDept(box.getDeptId());
//                    boxDept.setStatus("1");
//                    boxDept.setDelFlag("0");
//                    boxDeptMapper.insert(boxDept);
//                }
//                update.setBoxId(box.getId());
                update.setBoxNo(vo.getBoxNo());

                if (baseMapper.updateById(update) == 0) {
                    throw new ServiceException("更新上架财物失败");
                }

                /**
                 * 库位信息
                 */
                Locator locator = locatorMapper.selectById(update.getLocatorId());
                if (locator != null && StringUtils.isNotEmpty(vo.getLocatorStatus()) && vo.getLocatorStatus().equals("1")) {
                    Locator locatorNew = new Locator();
                    locatorNew.setId(locator.getId());
                    locatorNew.setStatus("2");
                    if (locatorMapper.updateById(locator) == 0) {
                        throw new ServiceException("更新库位状态失败");
                    }
                }

                /**
                 * 上架附件
                 */
                if (vo.getOss() != null && vo.getOss().size() > 0) {
                    vo.getOss().forEach(oss -> {
                        oss.setObjid(update.getId());
                        oss.setBuss("putDtl");
                        if (!ossMapper.insertOrUpdate(oss)) {
                            throw new ServiceException("更新上架附件失败");
                        }
                    });
                }


                InventoryBo inventoryBo = new InventoryBo();
                inventoryBo.setPno(update.getPno());
                inventoryBo.setStoreId(update.getStoreId());
                InventoryVo inventory = inventoryMapper.selectInventoryByBo(inventoryBo);
                Inventory inBo = new Inventory();
                BeanUtil.copyProperties(inventory, inBo);

                if (inventory == null) {

                    inBo = new Inventory();
                    inBo.setId(IdUtil.simpleUUID());
                    inBo.setPno(update.getPno());
                    inBo.setName(update.getName());
                    inBo.setInnums(update.getNums());
                    inBo.setNums(update.getNums());
                    inBo.setUnit(update.getUnit());
                    inBo.setDeals(0L);
                    inBo.setRnums(0L);
                    inBo.setTnums(0L);

                    PropertyVo property = propertyMapper.selectPropertyVoByPno(update.getPno());

                    inBo.setDeptId(property.getOfficeId());
                    inBo.setPics(update.getPics());
                    inBo.setDelFlag("0");
                    inBo.setIntime(new Date());
                    inBo.setStatus("0");

                } else {

                    /**
                     * 获取真实库存数
                     */
                    Long transfers = inventory.getTnums() != null ? inventory.getTnums() : 0L;
                    Long deals = inventory.getDeals() != null ? inventory.getDeals() : 0L;
                    Long returnNums = inventory.getRnums() != null ? inventory.getRnums() : 0L;
                    inBo.setIntime(new Date());
                    inBo.setInnums(update.getNums());
                    Long realNums = update.getNums() - transfers - deals + returnNums;
                    inBo.setNums(realNums);
                }

                inBo.setStoreId(update.getStoreId());
                inBo.setAreaId(update.getAreaId());
                inBo.setLocatorId(update.getLocatorId());
                inBo.setQrcode(update.getQrcode());
                inBo.setBoxNo(update.getBoxNo());

                if (!inventoryMapper.insertOrUpdate(inBo)) {
                    throw new ServiceException("插入更新库存数据失败");
                }

                Property property = propertyMapper.selectOne(new LambdaQueryWrapper<Property>().eq(Property::getPno, update.getPno()));

                if (property != null) {
                    property.setLocatorId(update.getLocatorId());
                    property.setQrcode(update.getQrcode());
                    property.setBelongStoreId(update.getStoreId());
                    if (propertyMapper.updateById(property) == 0) {
                        throw new ServiceException("更新财物表数据失败");
                    }
                }
            }
        }
        return true;
    }

    @Override
    public Boolean countByPrintFlag(PutDtlBo bo) {

        PutDtl putDtl = baseMapper.selectById(bo.getId());
        Integer flags = 0;
        if (putDtl.getPrintFlag() > 0) {
            flags = putDtl.getPrintFlag() + bo.getPrintFlag();
        } else {
            flags = bo.getPrintFlag();
        }
        putDtl.setPrintFlag(flags);
        return baseMapper.updateById(putDtl) > 0;
    }

    @Override
    public void updatePutdtl(String key) {

        List<PutDtlVo> dlts = baseMapper.selectUpdateList(key);
        Integer index = 1;
        Integer cars = 1;
        if (dlts != null && dlts.size() > 0) {
            for (PutDtlVo item : dlts) {
                String qrcode = item.getQrcode();
                String[] qrcodes = qrcode.split("/");
                PropertyVo pvo = propertyMapper.selectVoOne(new LambdaQueryWrapper<Property>().eq(Property::getPno, item.getPno()));
                if (pvo != null) {
                    String region = deptMapper.selectById(pvo.getOfficeId()).getRegion();
                    qrcodes[1] = region;
                }
                item.setQrcode(StringUtils.join(qrcodes, "/"));

//                LocatorVo vo = locatorMapper.selectLocatorVoByID(item.getLocatorId());
//                String newQrcode = makeQrcode(vo);
//                String[] newQrcodes = newQrcode.split("/");
//                /**
//                 * 补充对应的区域编号
//                 */
//                if(StringUtils.isEmpty(newQrcodes[1]) || newQrcodes[1].equals("null")){
//                    PropertyVo pvo = propertyMapper.selectVoOne(new LambdaQueryWrapper<Property>().eq(Property::getPno,item.getPno()));
//                    if(vo != null){
//                        String region = deptMapper.selectById(pvo.getOfficeId()).getRegion();
//                        newQrcodes[1] = region;
//                    }
//                }
//                String newCode = StringUtils.join(newQrcodes,"/");
//                if(newQrcodes[0].equals("CL")){
//                    newQrcodes[newQrcodes.length - 2] = cars+"";
//                    newCode = StringUtils.join(newQrcodes,"/");
//                }else{
//                    newCode = newCode+"/"+index;
//                }
//
//                log.info("newCode::",newCode);

//                item.setQrcode(newCode);

                PutDtl dtl = baseMapper.selectById(item.getId());
                dtl.setQrcode(item.getQrcode());
                baseMapper.updateById(dtl);
                Property property = propertyMapper.selectOne(new LambdaQueryWrapper<Property>().eq(Property::getPno, item.getPno()));
                if (property != null) {
                    property.setQrcode(item.getQrcode());
                    propertyMapper.updateById(property);
                }
                Inventory inventory = inventoryMapper.selectOne(new LambdaQueryWrapper<Inventory>().eq(Inventory::getPno, item.getPno()));
                if (inventory != null) {
                    inventory.setQrcode(item.getQrcode());
                    inventoryMapper.updateById(inventory);
                }
//                if(newQrcodes[0].equals("CL")){
//                    cars ++;
//                }else {
//                    index ++;
//                }
            }
        }

    }

    public String makeQrcode(LocatorVo vo) {
        //获取库区
        StoreAreaVo storeAreaVo = storeAreaMapper.selectStoreAreaVoByID(vo.getAreaId());
        //获取货柜/车辆
        CabinetGroupVo cabinetGroupVo = cabinetGroupMapper.selectCabinetGroupVoByID(vo.getCabinetGroupId());

        //获取架子
        String cabintetNo = "";
        if (StringUtils.isNotEmpty(vo.getCabinetId())) {
            CabinetVo cabinetVo = cabinetMapper.selectCabinetVoByID(vo.getCabinetId());
            cabintetNo = cabinetVo.getCno();
            vo.setCabinetName(cabinetVo.getName());
        }


        String qrcode = storeAreaVo.getAno() + "/" + cabinetGroupVo.getRegion() + "/" + DateFormatUtils.format(new Date(), "yy/M") + "/";
        switch (storeAreaVo.getAno()) {
            case "CL":
                qrcode += cabinetGroupVo.getCno() + "/" + "1" + "/" + vo.getName();
                break;
            case "PT":
                if (StringUtils.isNotEmpty(vo.getShape())) {
                    qrcode += vo.getShape() + "/";
                }
                qrcode += cabinetGroupVo.getCno() + "/" + cabintetNo + "/" + (vo.getFloors() != null ? vo.getFloors() + "/" : "");
                if (StringUtils.isNotEmpty(vo.getShape()) && vo.getShape().equals("X1")) {
                    qrcode += vo.getBoxs() + "/";
                }
                break;
            case "GZ":
                qrcode += cabinetGroupVo.getCno() + "/" + vo.getName() + "/";
                break;
            case "DZ":
                qrcode += cabinetGroupVo.getCno() + "/" + vo.getName() + "/";
                break;
            case "ZX":
                if (vo.getFloors() != null) {
                    qrcode += vo.getFloors() + "/";
                } else {
                    qrcode = qrcode;
                }

                break;
            case "DX":
                qrcode = qrcode;
                break;
            default:
                break;
        }
        return qrcode;
    }

    /**
     * 保存前的数据校验
     *
     * @param entity 实体类数据
     */
    private void validEntityBeforeSave(PutDtl entity) {
        //TODO 做一些数据校验,如唯一约束
    }

    /**
     * 批量删除上架任务明细
     *
     * @param ids 需要删除的上架任务明细主键
     * @return 结果
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean deleteWithValidByIds(Collection<String> ids, Boolean isValid) {

        if (isValid) {
            //TODO 做一些业务上的校验,判断是否需要校验
        }
        return baseMapper.deleteBatchIds(ids) > 0;
    }

    @Override
    public List<SmartCabinetPutProtVo> queryDtlBySmartCabinetId(String smartCabinetId) {

        return baseMapper.smartCabinetGetProV2(smartCabinetId.trim());
    }


}
